package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;

import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.BusinessDTO;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

//服务人员

@RestController
@RequestMapping("Serve")
public class ServeController extends BaseController{

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;

    @Autowired
    @Qualifier("UserAppInfoServiceImplOne")
    private UserAppInfoService userAppInfoService;

    @Autowired
    @Qualifier("ServeServiceImplOne")
    private ServeService serveService;

    @Autowired
    @Qualifier("BusinessServiceImplOne")
    private BusinessService businessService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("BusinessStaffRelServiceImplOne")
    private BusinessStaffRelService businessStaffRelService;



    //政府管理员获取面板数据
    @RequestMapping(value = "Pannel", method = RequestMethod.POST)
    public MyResult Pannel(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Serve/Pannel");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);
            String governmentCode = staff.getGovernmentCode();

            List<BusinessDTO> listBusiness = businessService.getListBusinessDTOByGovernmentCode(governmentCode);
            int serveCount = 0;
            for(BusinessDTO item:listBusiness){
                List<Serve> listServe = serveService.getListByBusinessCode(item.getBusinessCode());
                serveCount += listServe.size();
            }


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("serveCount",serveCount);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Serve/Pannel", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }



    //添加
    @RequestMapping(value = "Add", method = RequestMethod.POST)
    @Transactional
    public MyResult Add(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Serve/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String password = jsonObject.getString("password");

            User user = userService.getByPhone(phone);
            if (user != null) {
                return failed("该手机号已注册");
            }

            User user1 = new User();
            String userCode = UUID.randomUUID().toString();
            user1.setUserCode(userCode);
            user1.setPhone(phone);
            user1.setPassword(getMD5Str(password));
            user1.setName(name);
            user1.setCreateTime(new Date());
            user1.setUserType(4);
            user1.setStaffCode(staffCode);
            user1.setGovernmentCode(staff.getGovernmentCode());

            userService.insert(user1);

            String idCard = jsonObject.getString("idCard");

            String ageNumber = idCard.substring(6, 10);     //年
            int ageNum = Integer.parseInt(ageNumber);
            System.out.println("ageNum = " + ageNum);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            String nowTime = simpleDateFormat.format(date);
            String nowTimeNumber = nowTime.substring(0, 4);
            System.out.println("nowTimeNumber = " + nowTimeNumber);
            int nowTimeNum = Integer.parseInt(nowTimeNumber);
            int age =nowTimeNum-ageNum;

            String genderNumber = idCard.substring(16, 17);  //身份证倒数第二位
            int genderNum = Integer.parseInt(genderNumber);
            int gender;
            if(genderNum%2==0){
                gender=0;
            }else {
                gender=1;
            }



            String serveCode = UUID.randomUUID().toString();

            BusinessStaffRel businessStaffRel =businessStaffRelService.getByStaffCode(staffCode);
            String businessCode =businessStaffRel.getBusinessCode();

            String address = jsonObject.getString("address");



            String img = jsonObject.getString("img");
            String serviceContent = jsonObject.getString("serviceContent");
            String serviceRegion = jsonObject.getString("serviceRegion");
            int serviceType = jsonObject.getInteger("serviceType");
            String personNum = jsonObject.getString("personNum");
            String qualification = jsonObject.getString("qualification");
            String healthCards = jsonObject.getString("healthCards");

            Serve serve = new Serve();
            serve.setName(name);
            serve.setPhone(phone);
            serve.setServeCode(serveCode);
            serve.setUserCode(userCode);
            serve.setBusinessCode(businessCode);
            serve.setAddress(address);
            serve.setGender(gender);
            serve.setIdCard(idCard);
            serve.setAge(age);
            serve.setImg(img);
            serve.setServiceContent(serviceContent);
            serve.setServiceRegion(serviceRegion);
            serve.setServiceType(serviceType);
            serve.setServiceStatus(0);
            serve.setPersonNum(personNum);
            serve.setQualification(qualification);
            serve.setHealthCards(healthCards);

            serveService.insert(serve);

            Object data = new Object[]{};
            return success(data);


        } catch (Exception e) {
            insertErrorForAffair("/Serve/Add!",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }
    }


    //编辑
    @RequestMapping(value = "Edit", method = RequestMethod.POST)
    @Transactional
    public MyResult Edit(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Serve/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Staff staff = staffService.getByStaffCode(staffCode);

            String serveCode = jsonObject.getString("serveCode");
            Serve serve = serveService.getByServeCode(serveCode);

            String userCode = serve.getUserCode();
            User user = userService.getByUserCode(userCode);

            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            String servePhone=serve.getPhone();

            if(!servePhone.equals(phone)){
                User user1 = userService.getByPhone(phone);
                if(user1!=null){
                    return failed("该手机号已注册！");
                }
            }



            user.setName(name);
            user.setPhone(phone);
            user.setStaffCode(staffCode);
            user.setGovernmentCode(staff.getGovernmentCode());

            userService.update(user);

            String idCard = jsonObject.getString("idCard");
            //年龄判断
            String ageNumber = idCard.substring(6, 10);     //年
            int ageNum = Integer.parseInt(ageNumber);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            String nowTime = simpleDateFormat.format(date);
            String nowTimeNumber = nowTime.substring(0, 4);
            int nowTimeNum = Integer.parseInt(nowTimeNumber);
            int age =nowTimeNum-ageNum;
            //性别判断
            String genderNumber = idCard.substring(16, 17);  //身份证倒数第二位
            int genderNum = Integer.parseInt(genderNumber);
            int gender;
            if(genderNum%2==0){
                gender=0;
            }else {
                gender=1;
            }


            BusinessStaffRel businessStaffRel =businessStaffRelService.getByStaffCode(staffCode);
            String businessCode =businessStaffRel.getBusinessCode();

            String address = jsonObject.getString("address");



            String img = jsonObject.getString("img");
            String serviceContent = jsonObject.getString("serviceContent");
            String serviceRegion = jsonObject.getString("serviceRegion");
            int serviceType = jsonObject.getInteger("serviceType");
            int serviceStatus=jsonObject.getInteger("serviceStatus");
            String personNum = jsonObject.getString("personNum");
            String qualification = jsonObject.getString("qualification");
            String healthCards = jsonObject.getString("healthCards");


            serve.setBusinessCode(businessCode);
            serve.setAddress(address);
            serve.setName(name);
            serve.setGender(gender);
            serve.setIdCard(idCard);
            serve.setAge(age);
            serve.setImg(img);
            serve.setServiceContent(serviceContent);
            serve.setServiceRegion(serviceRegion);
            serve.setServiceType(serviceType);
            serve.setServiceStatus(serviceStatus);
            serve.setPersonNum(personNum);
            serve.setQualification(qualification);
            serve.setHealthCards(healthCards);

            serveService.update(serve);

            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertErrorForAffair("/Serve/Edit!",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }
    }


    //列表
    @RequestMapping(value = "Page",method = RequestMethod.POST)
    public   MyResult Page(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Serve/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            int pageIndex=jsonObject.getInteger("pageIndex");
            int pageSize=jsonObject.getInteger("pageSize");
            String name=jsonObject.getString("name");
            int serviceStatus=jsonObject.getInteger("serviceStatus");




            BusinessStaffRel businessStaffRel =businessStaffRelService.getByStaffCode(staffCode);
            String businessCode =businessStaffRel.getBusinessCode();

            PageInfo<Serve> servePageInfo=serveService.getPageList(pageIndex,pageSize,name,serviceStatus,businessCode);
            return success(servePageInfo);

        } catch (Exception e) {
            insertError("/Serve/Page",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //设备添加服务人员
    @RequestMapping(value = "DeviceAddServe", method = RequestMethod.POST)
    public MyResult DeviceAddServe(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Serve/DeviceAddServe");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Staff staff = staffService.getByStaffCode(staffCode);
            String governmentCode = staff.getGovernmentCode();

            List<BusinessDTO> businessList = businessService.getListBusinessDTOByGovernmentCode(governmentCode);
            for (BusinessDTO businessDTO1 : businessList) {
                List<Serve> serveList = serveService.getListByBusinessCode(businessDTO1.getBusinessCode());
                businessDTO1.setServeList(serveList);
                User user =userService.getByUserCode(businessDTO1.getUserCode());
                String businessName=user.getName();
                businessDTO1.setBusinessName(businessName);
            }
            return success(businessList);
        } catch (Exception e) {
            insertError("/Serve/DeviceAddServe",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    // 商家  设备添加服务人员
    @RequestMapping(value = "BusinessDeviceAddServe",method = RequestMethod.POST)
    public MyResult BusinessDeviceAddServe(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Serve/BusinessDeviceAddServe");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            BusinessStaffRel businessStaffRel=businessStaffRelService.getByStaffCode(staffCode);
            String businessCode=businessStaffRel.getBusinessCode();
            List<Serve> serveList =serveService.getListByBusinessCode(businessCode);
            return success(serveList);
        } catch (Exception e) {
            insertError("/Serve/BusinessDeviceAddServe",jsonObject.toJSONString(),getExceptionMsg(e),"api");
             return anomalous(getExceptionMsg(e));
        }
    }


    //--------------------------------------------------



    //登录
    @RequestMapping(value = "Login",method = RequestMethod.POST)
    public MyResult Login(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String phone = jsonObject.getString("phone");
            String password = jsonObject.getString("password");
            String os = jsonObject.getString("os");
            String regId = jsonObject.getString("regId");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Serve/Login");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByPhoneAndPassword(phone,getMD5Str(password));
            if(user == null){
                return failed("用户名或者密码错误");
            }
            if(user.getStatus() == 2){
                return failed("账户被禁用");
            }
            if(user.getUserType() != 4){
                return failed("账户类型错误");
            }


            UserAppInfo userAppInfo = userAppInfoService.getByUserCode(user.getUserCode());
            if(userAppInfo == null){
                userAppInfo = new UserAppInfo();
                userAppInfo.setUserAppInfoCode(UUID.randomUUID().toString());
                userAppInfo.setUserCode(user.getUserCode());
                userAppInfo.setAppOs(os);
                userAppInfo.setRegId(regId);
                userAppInfoService.insert(userAppInfo);
            }
            else{

                if(!regId.equals("")){
                    if(!os.equals(userAppInfo.getAppOs()) || !regId.equals(userAppInfo.getRegId())){
                        userAppInfo.setAppOs(os);
                        userAppInfo.setRegId(regId);
                        userAppInfoService.update(userAppInfo);
                    }
                }
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("user",user);
            jsonObject1.put("userAppInfo",userAppInfo);

            return success(jsonObject1);

        }catch (Exception e){
            insertError("/Serve/Login",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //退出
    @RequestMapping(value = "LoginOut",method = RequestMethod.POST)
    public MyResult LoginOut(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Serve/LoginOut");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            UserAppInfo userAppInfo = userAppInfoService.getByUserCode(userCode);
            if(userAppInfo == null){
                return failed("用户不存在");
            }else{
                userAppInfo.setAppOs("");
                userAppInfo.setRegId("");
                userAppInfoService.update(userAppInfo);
            }

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);

        }catch (Exception e){
            insertError("/Serve/LoginOut",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //检查登录
    @RequestMapping(value = "CheckLogin",method = RequestMethod.POST)
    public MyResult CheckLogin(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");
            String os = jsonObject.getString("os");
            String regId = jsonObject.getString("regId");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Serve/CheckLogin");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            UserAppInfo userAppInfo = userAppInfoService.getByUserCode(userCode);
            if(userAppInfo == null){
                return failed("用户不存在");
            }

            Boolean loginOut = false;
            if(!userAppInfo.getAppOs().equals(os) || !userAppInfo.getRegId().equals(regId)){
                loginOut = true;
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("loginOut",loginOut);
            return success(jsonObject1);

        }catch (Exception e){
            insertError("/Serve/CheckLogin",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }






}
